# -*- coding:utf-8 -*-
import datetime
import pandas as pd
import numpy as np
import os
import copy
import Core.Config as Config
import Core.Gadget as Gadget


#
def calc_total_stock_cap_change_ratio_index(database, datetime1, datetime2):
    #
    day_list = Gadget.generate_trading_days(database, datetime1, datetime2, as_df=False)
    df_last = pd.DataFrame()
    res_data = []
    for day in day_list:
        df_now = database.GetDataFrame("financial_data", "stock_daily_bar", filter=[("date", day)], projection=["date", "symbol", "close", "total_shares"])
        df_now["cap"] = df_now["close"] * df_now["total_shares"]
        #
        if not df_last.empty:
            df = pd.merge(df_last, df_now, how="left", on="symbol")
            df["cap_change"] = df["cap_y"] - df["cap_x"]
            total_cap_change = df['cap_change'].sum()
            total_cap_t1 = df['cap_x'].sum()
            total_cap_return = total_cap_change / total_cap_t1
            print(day, total_cap_return, len(df))
            doc = {}
            doc["day"] = day
            doc["total_cap_return"] = total_cap_return
            doc["num_stock"] = len(df)

            res_data.append(doc)

        df_last = df_now.copy()
    #
    df_res = pd.DataFrame(res_data)
    df_res["cap_change_index"] = pd.DataFrame.cumprod(df_res["total_cap_return"] + 1)
    #
    path = r"C:\Users\kkwoo\Documents\Systematic_Factor"
    df_res.to_excel(path + "\\" + "total_stock_cap_change_ratio_index_" + Gadget.ToDateString(datetime1) + "_" + Gadget.ToDateString(datetime2) + ".xlsx", index=False)



if __name__ == '__main__':

    # ---Connecting Database---
    path_filename = os.getcwd() + "\..\Config\config_local.json"
    database = Config.create_database(database_type="MySQL", config_file=path_filename, config_field="MySQL")

    #
    datetime1 = datetime.datetime(2016,1,1)
    datetime2 = datetime.datetime(2020,1,6)
    calc_total_stock_cap_change_ratio_index(database, datetime1, datetime2)